package com.zx._03_并发.chapter_06_compent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件CountDownLatch
 */
@Slf4j
public class Demo_01_CountDownLatch {

    public static void main(String[] args) {
        int ThreadToatl = 10;//线程数
        final CountDownLatch downLatch = new CountDownLatch(ThreadToatl);

        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < ThreadToatl; i++) {
            pool.execute(() -> {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("thread run");
                downLatch.countDown();
            });
        }
        log.info("shutdown");
        pool.shutdown();
        try {
            log.info("await");
            downLatch.await();//让主线程等待工作线程，方式一
            //downLatch.await(1, TimeUnit.SECONDS);//让主线程等待工作线程,1秒钟，方式二
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("shutdownNow");
        pool.shutdownNow();
    }
}
